// 获取全局 app 实例
const app = getApp();
const { IoTVsp, IoTVspEvent, modeType } = requirePlugin('IoTVsp');
import { getAlipaySignParam } from '../../assets/js/api.js';

Page({
  data: {
    employee: {
      name: '',
      mobile: '',
      jobNum: ''
    },
    IoTVspConfig: {
      iotUniqueId: '',
      isvPid: '',
      orgOutId: '',
      enterPriseId: '',
      signStr: ''
    },
    disabled: true
  },
  onReady() {
    // 页面加载完成
    // 跳转到开通结果时监听上报结果数据
    IoTVsp.addEventListener(IoTVspEvent.query, (data) => {
      // 当跳转至开通结果页，data中能获取到上报到信息，不需要点击完成拿到信息
      console.log('========query==========');
      console.log(data);
    });
    // 开通结果页点击完成返回事件
    IoTVsp.addEventListener(IoTVspEvent.back, (data) => {
      //若配置不跳转至默认开通成功页，则开通成功后执行此回调
      //若为团餐场景，已开通按钮点击后执行此回调
      // 一般在此处跳转回自己的页面
      console.log('========back==========')
      console.log(data);
      my.navigateTo({
        url: '/pages/result/result'
      })
    });
     // 错误事件监听
    IoTVsp.addEventListener(IoTVspEvent.result, (data) => {
      console.log('========result==========')
      console.log(data);
    });
  },
  async onLoad() {
    try {
      let res = await app.getEmployeeInfo();
      this.setData({
        employee: res
      })
    } catch(err) {
      my.removeStorageSync({
        key: 'token',
      });
      my.showToast({
        type: 'fail',
        content: err.message,
        duration: 3000
      });
    }
    this.getMyAuthCode();
  },
  // 按需添加 移除监听事件
  removeAllListener() {
    // 移除所有的 IoTVspEvent.back 的监听事件
    IoTVsp.removeAllListeners(IoTVspEvent.back);
    // 移除所有的 IoTVspEvent.result 的监听事件
    IoTVsp.removeAllListeners(IoTVspEvent.result);
    // 移除所有的 IoTVspEvent.query 的监听事件
    IoTVsp.removeAllListeners(IoTVspEvent.query);
  },
  async startComponent(e) {
    const { type } = e.currentTarget.dataset;
    const { isvPid, orgOutId, enterPriseId, signStr, iotUniqueId } = this.data.IoTVspConfig;
    // 如果有多处使用该插件，建议先移除监听，再添加监听事件
    // this.removeAllListener();
    const res = await IoTVsp.start({
      mode: modeType[type], // type改成modeType中需要启动的mode
      config: {
        uniqueId: iotUniqueId || '',
        isvPid: isvPid,
        orgOutId: orgOutId,   
        componentOutId: 'facepay_epc_agree_nores',
        enterPriseList: {
          enterPriseId: enterPriseId,
          process: 'sign|withHold',
          withHoldParam: signStr,
          appId: 'appid',
          returnUrl: 'pages/result/result',
        }
      },
    });
    console.log(res);
  },
  getMyAuthCode() {
    my.getAuthCode({
      scopes: ['auth_user'],
      success: (res) => {
        let authCode = res.authCode;
        this.getIoTVspParams(authCode);
      },
      fail: (err) => {
        my.showToast({
          type: 'fail',
          content: JSON.stringify(err),
          duration: 3000
        });
      },
    });
  },
  async getIoTVspParams(code) {
    let params = {
      authCode: code
    }
    let res = await getAlipaySignParam(params);
    if (res.code === 0) {
      let result = res.data;
      this.setData({
        IoTVspConfig: {
          isvPid: result.isvPid,
          orgOutId: result.orgOutId,
          enterPriseId: result.enterPriseId,
          signStr: result.signStr,
          iotUniqueId: result.iotUniqueId
        },
        disabled: false
      })
    } else {
      my.showToast({
        type: 'fail',
        content: res.message,
        duration: 3000
      });
    }
  }
});